package com.moto.service.impl;

import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.moto.bean.PostsFriendBean;
import com.moto.bean.PostsTradeBean;
import com.moto.common.PostType;
import com.moto.entity.MotoUser;
import com.moto.entity.Posts;
import com.moto.entity.PostsFriend;
import com.moto.entity.PostsTrade;
import com.moto.repository.MotoUserRepository;
import com.moto.repository.PostsFriendApplyRepository;
import com.moto.repository.PostsFriendRepository;
import com.moto.repository.PostsRepository;
import com.moto.repository.PostsTradeRepository;
import com.moto.service.PostsService;

@Service("postsService")
public class PostsServiceImpl implements PostsService {

	private static final Logger LOG = Logger.getLogger(PostsServiceImpl.class);
	@Autowired
	private PostsRepository postsRepository;
	@Autowired
	private PostsFriendRepository postsFriendRepository;
	@Autowired
	private MotoUserRepository motoUserRepository;
	@Autowired
	private PostsFriendApplyRepository postsFriendApplyRepository;
	@Autowired
	private PostsTradeRepository postsTradeRepository;

	private final String prefix = "[精华帖]";

	//帖子加精时，数据库中主题词字段没有加上[精华帖]
	@Override
	public boolean addDigest(String postsId) {
		LOG.debug("帖子加精，帖子ID = " + postsId);

		Posts posts = postsRepository.selectByPrimaryKey(postsId);

		Map<String, String> map = Maps.newHashMap();
		map.put("postsSubject", prefix + posts.getPostsSubject());
		map.put("postsId", postsId);
		int digest = postsRepository.addDigest(map);
		if (digest == 1) {
			return true;
		} else {
			return false;
		}
	}
	
	@Override
	public boolean deleteDegest(String postsId) {
		LOG.debug("帖子去精，帖子ID = " + postsId);
		Posts posts = postsRepository.selectByPrimaryKey(postsId);
		String subject = posts.getPostsSubject();
		String substring =
				subject.substring(subject.lastIndexOf(prefix) + prefix.length(), subject.length());

		Map<String, String> map = Maps.newHashMap();
		map.put("postsSubject", substring);
		map.put("postsId", postsId);

		int digest = postsRepository.deleteDigest(map);
		if (digest == 1) {
			return true;
		} else {
			return false;
		}
	}

	/**
	 * 查询组队贴
	 */
	@Override
	public List<PostsFriendBean> getTeamPostsList() {
		LOG.debug("分页查询组队贴");
		List<Posts> postsList = postsRepository.getAllByType(PostType.POST_TYPE_FRIEND);
		List<PostsFriendBean> list = copyPostsFriendBean(postsList);
		// 第二步，根据ID去POSTS_FRIEND表中查询，去顶lack

		/*
		Page<Posts> page = (Page<Posts>) postsList;

		Page<PostsFriendBean> beanpage = new Page<PostsFriendBean>();
		beanpage.setCount(page.isCount());
		beanpage.setPageNum(page.getPageNum());
		beanpage.setPageSize(page.getPageSize());
		beanpage.setStartRow(page.getStartRow());
		beanpage.setEndRow(page.getEndRow());
		beanpage.setTotal(page.getTotal());
		beanpage.setPages(page.getPages());
		beanpage.setCountSignal(page.getCountSignal());
		beanpage.setOrderBy(page.getOrderBy());
		beanpage.setOrderByOnly(page.isOrderByOnly());
		beanpage.setReasonable(page.getReasonable());
		beanpage.setPageSizeZero(page.getPageSizeZero());
		beanpage.addAll(list);

		Collections.sort(list, new Comparator<PostsFriendBean>() {
			@Override
			public int compare(PostsFriendBean o1, PostsFriendBean o2) {
				String postsUpdatetime = o1.getPostsUpdateTime();
				String postsUpdatetime2 = o2.getPostsUpdateTime();

				Long t1 = Long.valueOf(postsUpdatetime);
				Long t2 = Long.valueOf(postsUpdatetime2);
				if (t1 > t2) {
					return -1;
				}
				if (t1 == t2) {
					return 0;
				}
				return 1;
			}
		});

		return beanpage;
		*/
		return list;
	}



	/**
	 * 关联查询
	 * 
	 * @param postsList
	 * @return
	 */
	private List<PostsFriendBean> copyPostsFriendBean(List<Posts> postsList) {
		List<PostsFriendBean> lists = Lists.newArrayListWithCapacity(postsList.size());
		for (Posts posts : postsList) {
			PostsFriend postsFriend = postsFriendRepository.selectByPostsId(posts.getPostsId());
			PostsFriendBean bean = new PostsFriendBean();
			bean.setPostsArea(posts.getPostsArea());
			bean.setPostsAssembleTime(postsFriend.getPostsAssembleTime());
			bean.setPostsComment(posts.getPostsComment());
			bean.setPostsContent(posts.getPostsContent());
			bean.setPostsCreatetime(posts.getPostsCreatetime());
			bean.setPostsDestination(postsFriend.getPostsDestination());
			bean.setPostsId(postsFriend.getPostsId());
			bean.setPostsLike(posts.getPostsLike());
			bean.setPostsPhone(postsFriend.getPostsPhone());
			bean.setPostsPics(posts.getPostsPics());
			bean.setPostsPicsSize(posts.getPostsPicsSize());
			bean.setPostsPicsDesc(posts.getPostsPicsDesc());
			bean.setPostsPopulation(postsFriend.getPostsPopulation());
			bean.setPostsRead(posts.getPostsRead());
			bean.setPostsRendezvous(postsFriend.getPostsRendezvous());
			if(null == posts.getPostsSubject()){
				bean.setPostsSubject("--");
			}else{
				bean.setPostsSubject(posts.getPostsSubject());
			}
			bean.setPostsType(posts.getPostsType());
			bean.setPostsUpdateTime(posts.getPostsUpdateTime());
			bean.setPostsIsElite(posts.getPostsIsElite());
			MotoUser motoUser = motoUserRepository.selectByPrimaryKey(posts.getPostUserId());
			bean.setPostsUser(motoUser);
			int applyCount = postsFriendApplyRepository.selectApplyCount(posts.getPostsId());
			Long count = postsFriend.getPostsPopulation();

			if (0 == applyCount) {
				bean.setLack(count);
			} else {
				Long applyCountLong = (long) applyCount;
				Long lack = count - applyCountLong;
				bean.setLack(lack);
			}
			lists.add(bean);
		}
		return lists;
	}

	@Override
	public List<PostsTradeBean> getTradePostsList() {
		LOG.debug("分页查询组队贴");
		List<Posts> postsList = postsRepository.getAllByType(PostType.POST_TYPE_TRADE);
		List<PostsTradeBean> list = copyPostsTradeBean(postsList);
		
		/*// 第二步，根据ID去POSTS_FRIEND表中查询，去顶lack
		Page<Posts> page = (Page<Posts>) postsList;

		Page<PostsTradeBean> beanpage = new Page<PostsTradeBean>();
		beanpage.setCount(page.isCount());
		beanpage.setPageNum(page.getPageNum());
		beanpage.setPageSize(page.getPageSize());
		beanpage.setStartRow(page.getStartRow());
		beanpage.setEndRow(page.getEndRow());
		beanpage.setTotal(page.getTotal());
		beanpage.setPages(page.getPages());
		beanpage.setCountSignal(page.getCountSignal());
		beanpage.setOrderBy(page.getOrderBy());
		beanpage.setOrderByOnly(page.isOrderByOnly());
		beanpage.setReasonable(page.getReasonable());
		beanpage.setPageSizeZero(page.getPageSizeZero());
		beanpage.addAll(list);

		Collections.sort(list, new Comparator<PostsTradeBean>() {
			@Override
			public int compare(PostsTradeBean o1, PostsTradeBean o2) {
				String postsUpdatetime = o1.getPostsUpdateTime();
				String postsUpdatetime2 = o2.getPostsUpdateTime();

				Long t1 = Long.valueOf(postsUpdatetime);
				Long t2 = Long.valueOf(postsUpdatetime2);
				if (t1 > t2) {
					return -1;
				}
				if (t1 == t2) {
					return 0;
				}
				return 1;
			}
		});
		return beanpage;
		*/
		return list;
	}

	private List<PostsTradeBean> copyPostsTradeBean(List<Posts> postsList) {
		List<PostsTradeBean> lists = Lists.newArrayListWithExpectedSize(postsList.size());
		for (Posts posts : postsList) {
			PostsTrade postsTrade = postsTradeRepository.selectByPostsId(posts.getPostsId());
			PostsTradeBean postsTradeBean = new PostsTradeBean();
			postsTradeBean.setPostsArea(posts.getPostsArea());
			postsTradeBean.setPostsId(posts.getPostsId());
			postsTradeBean.setPostsMotoTime(postsTrade.getPostsMotoTime());
			postsTradeBean.setPostsTradeType(postsTrade.getPostsTradeType());

			if (null != posts.getPostsComment()) {
				postsTradeBean.setPostsComment(posts.getPostsComment());
			}
			if (null != posts.getPostsContent()) {
				postsTradeBean.setPostsContent(posts.getPostsContent());
			}
			if (null != posts.getPostsCreatetime()) {
				postsTradeBean.setPostsCreatetime(posts.getPostsCreatetime());
			}
			if (null != posts.getPostsLike()) {
				postsTradeBean.setPostsLike(posts.getPostsLike());
			}
			if (null != postsTrade.getPostsMotoCost()) {
				postsTradeBean.setPostsMotoCost(postsTrade.getPostsMotoCost());
			}
			if (null != postsTrade.getPostsMotoKilometer()) {
				postsTradeBean.setPostsMotoKilometer(postsTrade.getPostsMotoKilometer());
			}
			if (null != postsTrade.getPostsMotoModel()) {
				postsTradeBean.setPostsMotoModel(postsTrade.getPostsMotoModel());
			}
			if (null != postsTrade.getPostsMotoPhone()) {
				postsTradeBean.setPostsMotoPhone(postsTrade.getPostsMotoPhone());
			}
			if (null != postsTrade.getPostsMotoQuality()) {
				postsTradeBean.setPostsMotoQuality(postsTrade.getPostsMotoQuality());
			}
			if (null != posts.getPostsPics()) {
				postsTradeBean.setPostsPics(posts.getPostsPics());
			}
			if (null != posts.getPostsPicsDesc()) {
				postsTradeBean.setPostsPicsDesc(posts.getPostsPicsDesc());
			}
			if (null != posts.getPostsPicsSize()) {
				postsTradeBean.setPostsPicsSize(posts.getPostsPicsSize());
			}
			if (null != posts.getPostsRead()) {
				postsTradeBean.setPostsRead(posts.getPostsRead());
			}
			if (null != posts.getPostsSubject()) {
				postsTradeBean.setPostsSubject(posts.getPostsSubject());
			}else{
				postsTradeBean.setPostsSubject("--");
			}
			if (null != postsTrade.getPostsTradeName()) {
				postsTradeBean.setPostsTradeName(postsTrade.getPostsTradeName());
			}
			
			postsTradeBean.setPostsIsElite(posts.getPostsIsElite());
			postsTradeBean.setPostsType(posts.getPostsType());
			postsTradeBean.setPostsUpdateTime(posts.getPostsUpdateTime());
			MotoUser motoUser = motoUserRepository.selectByPrimaryKey(posts.getPostUserId());
			postsTradeBean.setPostsUser(motoUser);
			lists.add(postsTradeBean);
		}
		return lists;
	}

	@Override
	public List<Posts> getPicPosts() {
		LOG.debug("查询图文贴");
		return postsRepository.getAllByType(PostType.POST_TYPE_PIC);
	}

	@Override
	public List<Posts> getDiscoverPosts() {
		LOG.debug("查询发现贴");
		return postsRepository.getAllByType(PostType.POST_TYPE_DISCOVER);
	}

	@Override
	public int insert(Posts posts) {
		LOG.info("发布帖子："+posts.toString());
		return postsRepository.insert(posts);
	}

	@Override
	public Posts getPostsById(String postsId) {
		LOG.info("查询帖子："+postsId);
		return postsRepository.selectByPrimaryKey(postsId);
	}

	@Override
	public int deleteByPrimaryKey(String postsId) {
		LOG.info("删除帖子："+postsId);
		return postsRepository.deleteByPrimaryKey(postsId);
	}

	@Override
	public int updatePosts(String postsId, String newPic, String newPicDesc, String newPicSize) {
		LOG.info("修改帖子图片，贴子ID ="+postsId);
		Map<String,String> map = Maps.newHashMap();
		map.put("postsId", postsId);
		map.put("pic",newPic);
		map.put("picDesc",newPicDesc);
		map.put("picSize",newPicSize);
		
		return postsRepository.updatePosts(map);
	}

	@Override
	public int updateByPrimaryKeySelective(Posts posts) {
		return postsRepository.updateByPrimaryKeySelective(posts);
	}
}
